﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;
using WapChargingSDK;
//using Microsoft.Xna.Framework.GamerServices;

namespace NapThe
{
    public class NapTheQuaTangController : Controller
    {
        public static bool isRunning = false;
        public static int completed = 0;
        public static IGamePage igame= null;
       
        public void OnMessageBoxAction(IAsyncResult ar)
        {
        }

        public override void process(INapTheQuaTang p)
        {
            p.setRectangle1(0);
            p.setTextBlock("textBlock8", "");
            NapTheDienThoaiController.counter = 0;
            if (!p.getMaThe().Contains("mã"))
            {
                p.setMaThe(p.getMaThe().ToUpper());
            }
            if (nonCharOrNumExits(p.getMaThe()))
            {
               // MessageBox.Show("Mã số quà tặng phải là dạng ký tự hoặc chữ số (0-9, A-Z)!");
                 Report.contentOfMessage =
                     "Mã số quà tặng phải là dạng ký tự hoặc chữ số (0-9, A-Z)!";
                p.navigateWhenFail();
                return;
                
            }

            if (p.getMaThe().Length != 6)
            {
               // MessageBox.Show("Mã số quà tặng phải có đủ 6 ký tự hoặc chữ số");
                Report.contentOfMessage = "Mã số quà tặng phải có đủ 6 ký tự hoặc chữ số";
                p.navigateWhenFail();
                return;
            }

            string t = p.getMaThe();
            ServiceController s1 = new ServiceController();
            ServiceController.sent = false;
            if (s1.enableProcess("Wrong2.txt", "Timer2.txt"))
            {
                WebClient proxy = new WebClient();
                //p.newTimer.Start();
                p.processTimer("Start");
                proxy.DownloadStringCompleted += (sender, e) =>
                {
                    NapTheDienThoaiController.counter = 0;
                    p.processTimer("Stop");

                    if (e.Error == null)
                    {
                        p.setTextBlock("textBlock8", "100% completed");
                        p.setRectangle1((double)4 * 185);
                        string data = e.Result;
                        ServiceController s = ServiceController.getNapThe(data);
                        ServiceController.sent = true;
                        string t1 = s.show();
                        Report.contentOfMessage  =  t1;
                        napTheQuaTang(s, p);
                        isRunning = false;
                    }
                    else
                    {
                         Report.contentOfMessage =
                             "Không truy cập được vào mạng Internet!";
                        isRunning = false;
                        NapTheDienThoaiController.counter = 0;
                        p.navigateWhenFail();
                      //  MessageBox.Show("Không truy cập được vào mạng Internet!");
                    }
                };

                isRunning = true;
                //proxy.DownloadStringAsync(new Uri("http://xml.yome.vn/coupon/index/pid/3/code/"
                //+ t +
                //"/child/1"
                //    , UriKind.Absolute));
                string[] coupon = getCouponLink();
                string noCache = DateTime.Now.ToLongTimeString();
                proxy.DownloadStringAsync(new Uri(coupon[0]
                + t +
                coupon[1] + "?t=" + noCache
                    , UriKind.Absolute));
            }
            else
            {
                isRunning = false;
                NapTheDienThoaiController.counter = 0;
                Report.contentOfMessage = ServiceController.x;
                p.navigateWhenFail();
                
            }

            return;
        }

        public static void napTheQuaTang(ServiceController s, INapTheQuaTang p)
        {
            bool x = s.enableProcess("Wrong2.txt", "Timer2.txt");

            if (s is ServiceP2)
            {
                storeMoney(ServiceController.x);
                completed = 1;
                //Controller.checkMoney = false;
                if (p != null)
                {
                    p.navigateWhenFail();
                }
               
            }
            else
            {
                p.navigateWhenFail();
            }

            //storeMoney("1000");
        }

        public bool isEnoughMoney()
        {
            bool enough = false;
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            int currMoney = 100;
            string myString = "";
            if (storage.FileExists("Money.txt"))
            {
                IsolatedStorageFileStream fileStream = storage.OpenFile("Money.txt", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    myString = reader.ReadLine();
                    myString = removeFirst(myString);
                    myString = NapTheDienThoaiController.Decrypt(myString,
                        "bkth83sh48jd92pq94hn81c0b47j32m6",
                        "5t93v31hg5yg9hs");
                    currMoney = Int32.Parse(parse(myString));

                    //if (currMoney >= 300)
                    //{
                    currMoney -= 300;
                    MessageBox.Show("" + currMoney);
                    //enough = true;
                    //}
                    reader.Close();
                    reader.Dispose();
                }
                fileStream.Close();
                fileStream.Dispose();
                //MessageBox.Show(myString);
            }
            else
            {
                currMoney -= 300;
            }

            FileStream stream = storage.OpenFile("Money.txt", FileMode.Create); // Open a file in Create mode
            BinaryWriter writer = new BinaryWriter(stream);
            myString = "" + currMoney;
            if (currMoney >= 0)
            {
                enough = true;
            }
            else
            {
                currMoney = 0;
            }
            myString = NapTheDienThoaiController.Encrypt(myString,
                        "bkth83sh48jd92pq94hn81c0b47j32m6",
                        "5t93v31hg5yg9hs");
            writer.Write(myString);
            writer.Close();
            writer.Dispose();
            stream.Close();
            stream.Dispose();

            storage.Dispose();
            return enough;
        }

        public static void storeMoney(string money)
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            int addMoney = Int32.Parse(parse(money));
            addMoney = ServiceController.getXu(addMoney);
            int finalMoney = addMoney;
            string myString = "";

            if (storage.FileExists("Money.txt"))
            {
                IsolatedStorageFileStream fileStream = storage.OpenFile("Money.txt", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    myString = reader.ReadLine();
                    myString = removeFirst(myString);
                    myString = NapTheDienThoaiController.Decrypt(myString,
                        "bkth83sh48jd92pq94hn81c0b47j32m6",
                        "5t93v31hg5yg9hs");
                    int currMoney = Int32.Parse(parse(myString));

                    finalMoney = currMoney + addMoney;
                    Controller.showAddedMoney(finalMoney, addMoney);
                
                    reader.Close();
                    reader.Dispose();
                }
                fileStream.Close();
                fileStream.Dispose();
                //MessageBox.Show(myString);
            }
            else
            {
                finalMoney += 3000;
            }

            myString = "" + finalMoney; //MessageBox.Show("Get from Money.txt: " + myString);

            FileStream stream = storage.OpenFile("Money.txt", FileMode.Create); // Open a file in Create mode
            BinaryWriter writer = new BinaryWriter(stream);
            myString = NapTheDienThoaiController.Encrypt(myString,
                        "bkth83sh48jd92pq94hn81c0b47j32m6",
                        "5t93v31hg5yg9hs");
            writer.Write(myString);
            writer.Close();
            writer.Dispose();
            stream.Close();
            stream.Dispose();

            if (storage.FileExists("Timer2.txt"))
            {
                storage.DeleteFile("Timer2.txt");
            }

            if (storage.FileExists("Wrong2.txt"))
            {
                storage.DeleteFile("Wrong2.txt");
            }

            storage.Dispose();

        }

        

        private static string removeFirst(string t)
        {
            return t.Substring(1);
        }

        private static string parse(string x)
        {
            string t = "";
            char[] array = x.ToCharArray();
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] >= '0' && array[i] <= '9')
                {
                    t = t + array[i];
                }
            }

            return t;
        }

        
        private bool nonCharOrNumExits(string t)
        {
            bool found = false;
            int i = 0;
            while (!found && i < t.Length)
            {
                if (!((t[i] >= '0' && t[i] <= '9') || (t[i] >= 'A' && t[i] <= 'Z')))
                {
                    found = true;
                }
                i++;
            }
            return found;
        }

        private static string[] getCouponLink()
        {
            string[] x = new string[2];
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            if (storage.FileExists("A\\Coupon.txt"))
            {
                IsolatedStorageFileStream fileStream = storage.OpenFile("A\\Coupon.txt", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    x[0] = reader.ReadLine();
                    x[1] = reader.ReadLine();

                    reader.Close();
                    reader.Dispose();
                }
                fileStream.Close();
                fileStream.Dispose();
            }
            storage.Dispose();

            return x;
        }
        
    }
}